import ResponseCode from '@/constants/ResponseCode'
import SystemConstant from '@/constants/System'
import {$ajax} from '@/utils/src/uAjax'
import $msgBox from '@/utils/src/message-box'
import router from '../router'

const ctx = SystemConstant.CTX

// $ajax.interceptors.response.use(function (response) {
//   // 未登录时的判断
//   if (response.headers['content-type'] === 'text/html') {
//     location.href = ctx
//   }
//   return response
// })

/* opt: {failedW, successW} */

/* opt: {失败弹框} */
function handleResponse (response, success, failed, opt) {
  const vm = router.app
  const data = response.data
  if (data.code === ResponseCode.SUCCESS) {
    success(data)
    if (opt.successW) {
      $msgBox.success(data.msg)
    }
  } else if (data.code === ResponseCode.UNLOGIN) {
    // 如果不是登录页面则跳转登录页面
    if (vm.$route.path !== '/login') {
      vm.$router.push({
        path: '/login',
        query: {
          redirect: vm.$route.fullPath
        }
      })
    }
  } else if (data.code === ResponseCode.WARNING) {
    console.warn(data.msg)
    failed(data)
  } else {
    if (opt.failedW) {
      $msgBox.error(data.msg)
    }
    failed(data)
  }
}

export default {
  // 获取带上下文的url地址
  getUrl: function (url) {
    return ctx + url
  },
  makeQuery (module, model) {
    const funcName = 'query' + model + 'Page'
    const url = SystemConstant.CTX + '/api/' + module + '/' + funcName
    return function (page = 0, pageSize = 10, param = {}) {
      // es6语法,Promise
      return new Promise((resolve, reject) => {
        $ajax.get(url, {
          params: {
            _r: new Date().getTime(),
            page: page,
            pageSize: pageSize,
            ...param // es7语法,对象展开运算符
          }
        }).then(response => {
          handleResponse(response, resolve, reject, {extra: {}, successW: false, failedW: true, canCancel: true, needRedirect: false})
        }).catch(e => {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  makeDetail (module, model) {
    const funcName = 'detail' + model
    const url = SystemConstant.CTX + '/api/' + module + '/' + funcName
    return function (params = {}) {
      // es6语法,Promise
      return new Promise((resolve, reject) => {
        $ajax.get(url, {
          params: {
            _r: new Date().getTime(),
            ...params
          }
        }).then(response => {
          handleResponse(response, resolve, reject, {extra: {}, successW: false, failedW: true, canCancel: true, needRedirect: false})
        }).catch(e => {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  makeDelete (module, model) {
    const funcName = 'delete' + model
    const url = SystemConstant.CTX + '/api/' + module + '/' + funcName
    return function (id) {
      // es6语法,Promise
      return new Promise((resolve, reject) => {
        // 自定义的post请求，参数可以省略qs.stringify
        $ajax.fPost(url, {
          id: id
        }).then(response => {
          handleResponse(response, resolve, reject, {extra: {}, successW: true, failedW: true, canCancel: true, needRedirect: false})
        }).catch(e => {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  makeBatchDelete (module, model) {
    const funcName = 'batchDelete' + model
    const url = SystemConstant.CTX + '/api/' + module + '/' + funcName
    return function (ids) {
      return new Promise((resolve, reject) => {
        $ajax.fPost(url, {
          ids: ids
        }).then(response => {
          handleResponse(response, resolve, reject, {extra: {}, successW: true, failedW: true, canCancel: true, needRedirect: false})
        }).catch(e => {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  makeAdd (module, model) {
    const funcName = 'add' + model
    const url = SystemConstant.CTX + '/api/' + module + '/' + funcName
    return function (record) {
      return new Promise((resolve, reject) => {
        $ajax.fPost(url, record).then(response => {
          handleResponse(response, resolve, reject, {extra: {}, successW: true, failedW: true, canCancel: true, needRedirect: false})
        }).catch(e => {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  makeUpdate (module, model) {
    const funcName = 'update' + model
    const url = SystemConstant.CTX + '/api/' + module + '/' + funcName
    return function (record) {
      return new Promise((resolve, reject) => {
        $ajax.fPost(url, record).then(response => {
          handleResponse(response, resolve, reject, {extra: {}, successW: true, failedW: true, canCancel: true, needRedirect: false})
        }).catch(e => {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  /**
   * get默认成功无弹窗，失败有弹窗
   * successW 成功是否弹窗
   * failedW 失败是否弹窗
   * extra 额外的参数
   */
  makeGet: function (url, options) {
    options = options || {}
    const _options = {extra: {}, successW: false, failedW: true}
    Object.assign(_options, options)
    return function (params) {
      params = params || {}
      return new Promise(function (resolve, reject) {
        $ajax.get(ctx + url, {
          params: Object.assign({
            _r: Date.now()
          }, _options.extra, params)
        }).then(function (response) {
          handleResponse(response, resolve, reject, _options)
        }).catch(function (e) {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  /**
   * post默认成功失败都有弹窗
   * successW 成功是否弹窗
   * failedW 失败是否弹窗
   * extra 额外的参数
   */
  makePost: function (url, options) {
    options = options || {}
    const _options = {extra: {}, successW: true, failedW: true}
    Object.assign(_options, options)
    return function (params) {
      params = params || {}
      return new Promise(function (resolve, reject) {
        $ajax.fPost(ctx + url, Object.assign({}, _options.extra, params)).then(function (response) {
          handleResponse(response, resolve, reject, _options)
        }).catch(function (e) {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  /**
   * post Json格式的数据
   * post默认成功失败都有弹窗
   * successW 成功是否弹窗
   * failedW 失败是否弹窗
   * extra 额外的参数
   */
  makeJPost: function (url, options) {
    options = options || {}
    const _options = {extra: {}, successW: true, failedW: true}
    Object.assign(_options, options)
    return function (params) {
      params = params || {}
      return new Promise(function (resolve, reject) {
        $ajax.jPost(ctx + url, Object.assign({}, _options.extra, params)).then(function (response) {
          handleResponse(response, resolve, reject, _options)
        }).catch(function (e) {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  },
  /**
   * get默认成功无弹窗，失败有弹窗, 支持pathVariable 例： /api/order/detail/{orderId}
   * successW 成功是否弹窗
   * failedW 失败是否弹窗
   * extra 额外的参数
   */
  restGet (url, options = {}) {
    let _options = {extra: {}, successW: false, failedW: true, canCancel: true, needRedirect: false}
    Object.assign(_options, options)
    return function (id) {
      return new Promise((resolve, reject) => {
        $ajax.get(SystemConstant.CTX + url + id, {
          params: {
            _r: new Date().getTime(),
            ..._options.extra
          }
        }).then(response => {
          handleResponse(response, resolve, reject, _options)
        }).catch(e => {
          $msgBox.error('网络异常')
          reject({
            msg: '网络异常'
          })
        })
      })
    }
  }
}
